//
//  M4LoginViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/8.
//

import UIKit
import ActiveLabel

class M4LoginViewController: M4BaseViewController {
    
    @IBOutlet weak var M4LoginView1: UIView!
    @IBOutlet weak var M4LoginNumberTF: UITextField!
    @IBOutlet weak var M4LoginView2: UIView!
    @IBOutlet weak var M4LoginCodeTF: UITextField!
    @IBOutlet weak var M4SendCodeButton: UIButton!
    @IBOutlet weak var M4SendVozButton: UIButton!
    @IBOutlet weak var M4LoginButton: UIButton!
    
    @IBOutlet weak var m4WhatsBtnH: NSLayoutConstraint!
    
    @IBOutlet weak var M4WhatsButton: UIButton!
    private var M4WhatsTimer: Timer?
    private var M4WhatsTimeInterval: TimeInterval = 0
    
    @IBOutlet weak var M4LoginProtocol: ActiveLabel!
    private var M4SmsTimer: Timer?
    private var M4SmsTimeInterval: TimeInterval = 0
    private var M4VozTimer: Timer?
    private var M4VozTimeInterval: TimeInterval = 0
    private var M4IsRegister: Int = 0
    private var M4EnterTime: Int = 0
    
    private var isHwatsCheckCOde: Int = 0

    
    @IBOutlet weak var M4Activelabel: M4DecriptionStringView!
    var M4BtnSelectedStatus: Bool = true
    
    var phoneBeginTime: Int = 0
    var codeData: (Int, Bool) = (0, false)
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        M4NavBarColor = .white
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(handleNotification(_:)),
                                               name: Notification.Name("M4ConfigDataManagerm4ConfigShare"),
                                               object: nil)
       
        
        
        
        M4UserDataManager.M4HasShowUploadPage = false
        
        M4Activelabel.c = self
        M4Activelabel.M4BtnSelectedStatus = { r in
            self.M4BtnSelectedStatus = r
        }
        
        M4EnterTime = Int(Date().timeIntervalSince1970 * 1000 )
        print("M4EnterTime1-\(M4EnterTime)")
//        M4BackIcon = "icon_back_black"
        M4NeedLeft = false
        M4NavRightItem()
        self.view.backgroundColor = .white
        M4LoginView1.layer.cornerRadius = 2
        M4LoginView1.layer.borderColor = COLOR_CCCCCC.cgColor
        M4LoginView1.layer.borderWidth = 0.5
        M4LoginNumberTF.keyboardType = .numberPad
        let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), .foregroundColor: COLOR_999999]
        M4LoginNumberTF.attributedPlaceholder = NSAttributedString(string: "Número de teléfono", attributes: attributes)
        M4LoginView2.layer.cornerRadius = 2
        M4LoginView2.layer.borderColor = COLOR_CCCCCC.cgColor
        M4LoginView2.layer.borderWidth = 0.5
        M4LoginCodeTF.keyboardType = .numberPad
        M4LoginCodeTF.attributedPlaceholder = NSAttributedString(string: "Código de verificación", attributes: attributes)
        M4SendCodeButton.layer.cornerRadius = 2
        M4SendCodeButton.M4EventUnavailable = true
        M4SendVozButton.M4EventUnavailable = true
        M4WhatsButton.M4EventUnavailable = true

        M4LoginButton.layer.cornerRadius = 2
//        M4LoginButton.M4EventUnavailable = true
//        let activeHandle = ActiveType.custom(pattern: "Aviso de Privacidad")
//        M4LoginProtocol.enabledTypes = [activeHandle]
//        M4LoginProtocol.text = "Al iniciar sesión o registrarse, usted acepta el Aviso de Privacidad"
//        M4LoginProtocol.customColor[activeHandle] = COLOR_00479D
//        M4LoginProtocol.handleCustomTap(for: activeHandle) { element in
//            let htmlVC = M4HtmlWebViewController()
//            htmlVC.M4WebTitle = "Aviso de Privacidad"
//            htmlVC.M4WebUrl = M4NetworkAPI.m4htmlPath.rawValue + "/nafvsdahgv"
//            htmlVC.M4OpenPrivacy = true
//            self.navigationController?.pushViewController(htmlVC, animated: true)
//        }
        M4LoginNumberTF.delegate = self
        M4LoginCodeTF.delegate = self
        
        M4LoginCodeTF.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
        
//        M4CheckTimer()
        
//        let param: [String : Any] = ["SaUyP": "ESP", "xW89K": M4UserDataManager.m4UserShare.M4Itemcode,"4wTmR":""]
//        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4loginWhats, .post, params: param), false) { model in
//           
//            if model.code == 1 {
//                
//            }else{
//                
//            }
//        }
    }
    
    @objc private func handleNotification(_ notification: Notification) {
        print("收到通知: \(notification)")
        if M4ConfigDataManager.m4ConfigShare.whatsAppStart {
            M4WhatsButton.isHidden = false
            m4WhatsBtnH.constant = 30
        }else{
            M4WhatsButton.isHidden = true
            m4WhatsBtnH.constant = 0
        }
        // 你可以从 notification.userInfo 中取出参数
    }
       

       @objc func textFieldDidChange(_ textField: UITextField) {
           guard let text = textField.text else { return }
           if text.count == 4 {
               print("输入到第4个字符了：\(text)")


               verifyCode(text)


           }
       }
    
    func verifyCode(_ input: String) {
           // 1. 验证码合法性
           guard input.range(of: #"^\d{4}$"#, options: .regularExpression) != nil else {

                   self.showImageTextToast(in: self.view, text: "El código de verificación es incorrecto, por favor vuelva a introducirlo", image: UIImage.init(named: "icon_fail22")!)
               return
           }
        
        M4LoginClick(self.M4LoginButton)
       }
    
    override func M4BackClick(sender: UIButton) {
        AppDelegate.keyWindow()?.rootViewController = M4TabBarViewController()
    }
    //整合流量的IDFA Adjust.idfa()
    //整合流量的adjust设备id  Adjust.adid()
    //整合流量的IDFV   Adjust.idfv()
   
    @IBAction func M4SendCodeClick(_ sender: UIButton) {
        self.view.endEditing(true)
        var phone = M4LoginNumberTF.text ?? ""
        if M4LoginNumberTF.text?.prefix(2) == "52" {
            phone = String(phone.suffix(from: phone.index(phone.startIndex, offsetBy: 2)))
            M4LoginNumberTF.text = phone
        }
//        M4GetUserInfoNet()
        M4SendMSMCodeNet()
    }
    
    @IBAction func M4SendVozClick(_ sender: UIButton) {
        self.view.endEditing(true)
        var phone = M4LoginNumberTF.text ?? ""
        if M4LoginNumberTF.text?.prefix(2) == "52" {
            phone = String(phone.suffix(from: phone.index(phone.startIndex, offsetBy: 2)))
            M4LoginNumberTF.text = phone
        }
//        M4GetUserInfoNet()
        M4VozCodeNet()
    }
    
    
    @IBAction func M4WhatsCheck(_ sender: UIButton) {
        self.view.endEditing(true)
        var phone = M4LoginNumberTF.text ?? ""
        if M4LoginNumberTF.text?.prefix(2) == "52" {
            phone = String(phone.suffix(from: phone.index(phone.startIndex, offsetBy: 2)))
            M4LoginNumberTF.text = phone
        }
//        M4GetUserInfoNet()
        sender.M4EventUnavailable = false

        M4WhatsCodeNet()
    }
    
    
    @IBAction func M4LoginClick(_ sender: UIButton) {
        self.view.endEditing(true)
        if M4BtnSelectedStatus == false {
            self.showImageTextToast(in: self.view, text: "Lea y acepte la divulgación de información", image: UIImage.init(named: "icon_fail22")!)

            sender.M4EventUnavailable = false
            return
        }
        let loading = M4LoadingAlertView()
        loading.M4LoadingAlertShow()
        M4GetUserInfoNet {
            self.M4LoginNet { 
                loading.M4AlertViewHidden()
            }
        }
        sender.M4EventUnavailable = false
    }
    
    private func M4ChangeCodeBtnUI(light: Bool) {
        M4SendCodeButton.backgroundColor = light ? COLOR_00479D : COLOR_EFEFEF
        M4SendCodeButton.setTitleColor(light ? .white : COLOR_999999, for: .normal)
        M4SendCodeButton.M4EventUnavailable = light ? false : true
        M4SendVozButton.setTitleColor(light ? COLOR_00479D : COLOR_999999, for: .normal)
        M4SendVozButton.M4EventUnavailable = light ? false : true
        
        M4WhatsButton.setTitleColor(light ? COLOR_00479D : COLOR_999999, for: .normal)
        M4WhatsButton.M4EventUnavailable = light ? false : true
        
    }
    
    private func M4CheckTimer() {
        let a = UserDefaults.standard.integer(forKey: "msm_code_start")
        let b = UserDefaults.standard.integer(forKey: "voz_code_start")
        let c = Int(Date().timeIntervalSince1970)
        
        let d1 = c - a
        let d2 = c - b
        if d1 < 60 {
            self.M4SmsTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.M4TimerCut(timer:)), userInfo: nil, repeats: true)
            RunLoop.main.add(self.M4SmsTimer!, forMode: .common)
        }
        
        if d2 < 60 {
            self.M4VozTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.M4TimerCut(timer:)), userInfo: nil, repeats: true)
            RunLoop.main.add(self.M4VozTimer!, forMode: .common)
        }
    }
    
    @objc private func M4TimerCut(timer: Timer) {
        let c = Int(Date().timeIntervalSince1970)
        if timer == M4SmsTimer {
            let a = UserDefaults.standard.integer(forKey: "msm_code_start")
            let b = c - a
            let d = 60 - b
            
            if d <= 0 {
                M4StopTimer(timer: timer)
                M4SendCodeButton.backgroundColor = COLOR_00479D
                M4SendCodeButton.setTitle("Código SMS", for: .normal)
                M4SendCodeButton.setTitleColor(.white, for: .normal)
                M4SendCodeButton.M4EventUnavailable = false
                //                M4LoginNumberTF.isUserInteractionEnabled = true
            }
            else {
                M4SendCodeButton.backgroundColor = COLOR_EFEFEF
                let titleStr = "\(String(format: "%02ds", d))"
                M4SendCodeButton.setTitle("Código SMS \(titleStr)", for: .normal)
                M4SendCodeButton.setTitleColor(COLOR_999999, for: .normal)
                //                M4LoginNumberTF.isUserInteractionEnabled = false
            }
        }
        else if timer == M4VozTimer{
            let a = UserDefaults.standard.integer(forKey: "voz_code_start")
            let b = c - a
            let d = 60 - b
            
            if d <= 0 {
                    M4StopTimer(timer: timer)
                    M4SendVozButton.setTitle("Solicitar código de voz", for: .normal)
                    M4SendVozButton.setTitleColor(COLOR_00479D, for: .normal)
                    M4SendVozButton.M4EventUnavailable = false
                    //                M4LoginNumberTF.isUserInteractionEnabled = true
            }else {
                M4SendVozButton.setTitleColor(COLOR_999999, for: .normal)
                let titleStr = "\(String(format: "%02ds", d))"
                M4SendVozButton.setTitle("Solicitar código de voz \(titleStr)", for: .normal)
                //                M4LoginNumberTF.isUserInteractionEnabled = false
            }
        }else {
            let a = UserDefaults.standard.integer(forKey: "Whats_code_start")
            let b = c - a
            let d = 60 - b
             
            if d <= 0 {
                    M4StopTimer(timer: timer)
                M4WhatsButton.setTitle("Recibir código por WhatsApp", for: .normal)
                M4WhatsButton.setTitleColor(COLOR_00479D, for: .normal)
                M4WhatsButton.M4EventUnavailable = false
                    //                M4LoginNumberTF.isUserInteractionEnabled = true
            }else {
                M4WhatsButton.setTitleColor(COLOR_999999, for: .normal)
                let titleStr = "\(String(format: "%02ds", d))"
                M4WhatsButton.setTitle("Recibir código por WhatsApp \(titleStr)", for: .normal)
                //                M4LoginNumberTF.isUserInteractionEnabled = false
            }
        }
    }
    
//    @objc private func M4TimerCut(timer: Timer) {
//        if timer == M4SmsTimer {
//            M4SmsTimeInterval -= 1
//            if M4SmsTimeInterval <= 0 {
//                M4StopTimer(timer: timer)
//                M4SendCodeButton.backgroundColor = COLOR_00479D
//                M4SendCodeButton.setTitle("Conseguir", for: .normal)
//                M4SendCodeButton.setTitleColor(.white, for: .normal)
//                M4SendCodeButton.M4EventUnavailable = false
////                M4LoginNumberTF.isUserInteractionEnabled = true
//            }
//            else {
//                M4SendCodeButton.backgroundColor = COLOR_EFEFEF
//                let seconds = Int(M4SmsTimeInterval) % 60
//                let titleStr = "\(String(format: "%02ds", seconds))"
//                M4SendCodeButton.setTitle("Reenviar \(titleStr)", for: .normal)
//                M4SendCodeButton.setTitleColor(COLOR_999999, for: .normal)
////                M4LoginNumberTF.isUserInteractionEnabled = false
//            }
//        }
//        else {
//            M4VozTimeInterval -= 1
//            if M4VozTimeInterval <= 0 {
//                M4StopTimer(timer: timer)
//                M4SendVozButton.setTitle("Obtener la verificación por mensaje de voz >", for: .normal)
//                M4SendVozButton.setTitleColor(COLOR_00479D, for: .normal)
//                M4SendVozButton.M4EventUnavailable = false
////                M4LoginNumberTF.isUserInteractionEnabled = true
//            }
//            else {
//                M4SendVozButton.setTitleColor(COLOR_999999, for: .normal)
//                let seconds = Int(M4VozTimeInterval) % 60
//                let titleStr = "\(String(format: "%02ds", seconds))"
//                M4SendVozButton.setTitle("Obtener la verificación por mensaje de voz \(titleStr) >", for: .normal)
////                M4LoginNumberTF.isUserInteractionEnabled = false
//            }
//        }
//    }
    
    private func M4StopTimer(timer: Timer) {
        if timer == M4SmsTimer {
            M4SmsTimer?.invalidate()
            M4SmsTimer = nil
            M4SmsTimeInterval = 0
        }
        else  if timer == M4VozTimer {
            M4VozTimer?.invalidate()
            M4VozTimer = nil
            M4VozTimeInterval = 0
        } else {
            M4WhatsTimer?.invalidate()
            M4WhatsTimer = nil
            M4WhatsTimeInterval = 0
        }
    }
    

  

        func showImageTextToast(in view: UIView, text: String, image: UIImage, duration: TimeInterval = 2.0) {
          

                let containerView = UIView()
                containerView.backgroundColor = UIColor.black.withAlphaComponent(0.8)
                containerView.layer.cornerRadius = 8
                containerView.clipsToBounds = true

                let imageView = UIImageView(image: image)
                imageView.contentMode = .scaleAspectFit
                imageView.setContentHuggingPriority(.required, for: .horizontal)
                imageView.translatesAutoresizingMaskIntoConstraints = false

                let label = UILabel()
                label.text = text
                label.textColor = .white
                label.font = UIFont.systemFont(ofSize: 15)
                label.numberOfLines = 0
                label.translatesAutoresizingMaskIntoConstraints = false

                let stackView = UIStackView(arrangedSubviews: [imageView, label])
                stackView.axis = .horizontal
                stackView.spacing = 8
                stackView.alignment = .center
                stackView.translatesAutoresizingMaskIntoConstraints = false

                containerView.addSubview(stackView)

                // 🔽 添加布局约束
                NSLayoutConstraint.activate([
                    stackView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 12),
                    stackView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -12),
                    stackView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 12),
                    stackView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -12),
                    imageView.widthAnchor.constraint(equalToConstant: 24),
                    imageView.heightAnchor.constraint(equalToConstant: 24),

                    // 🔽 关键：限制 label 最大宽度，才能让它换行
                    label.widthAnchor.constraint(lessThanOrEqualToConstant: UIScreen.main.bounds.width * 0.6)
                ])

                // 自动计算尺寸
                let maxWidth: CGFloat = UIScreen.main.bounds.width * 0.8
                let targetSize = CGSize(width: maxWidth, height: UIView.layoutFittingCompressedSize.height)
                let fittingSize = containerView.systemLayoutSizeFitting(
                    targetSize,
                    withHorizontalFittingPriority: .fittingSizeLevel,
                    verticalFittingPriority: .fittingSizeLevel
                )

                containerView.frame = CGRect(origin: .zero, size: fittingSize)

                view.showToast(containerView, duration: duration, position: .center)
            }
        
    
}

extension M4LoginViewController {
    
    func M4GetUserInfoNet(complete: @escaping () -> Void) {
        let param: [String : Any] = ["LeOCkJHyZ": "ESP", "APVgV": M4UserDataManager.m4UserShare.M4Itemcode, "Uxndby": "52\(M4LoginNumberTF.text ?? "")"]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4userInfo, .post, params: param), false) { model in
            complete()
            if model.code == 1 {
                let data = model.data as? [String : Any]
                self.M4IsRegister = data?["YRN"] as? Int ?? 0
                M4UserDataManager.m4UserShare.M4ProductCode = data?["trKs"] as? String ?? ""
                print(self.M4IsRegister)
            }
        }
    }
    
    private func M4SendMSMCodeNet() {
        isHwatsCheckCOde = 0
        codeData.0 = Int(Date().timeIntervalSince1970 * 1000)
        let phone = "52\(M4LoginNumberTF.text ?? "")"
        let param: [String : Any] = ["WIxTO": "ESP", "ChtW": M4UserDataManager.m4UserShare.M4Itemcode, "Taxz": phone, "JYJBl": "2", "IrWk": "adjust", "JtJQG": M4UserDataManager.m4UserShare.adjustIdfa, "Hsan": M4UserDataManager.m4UserShare.adjustAdid, "AfgFS": M4UserDataManager.m4UserShare.adjustIdfv, "WJVWZb": "Apple"]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4smsCode, .post, params: param)) { model in
            if model.code == 1 {
                self.isHwatsCheckCOde = 0

                if self.M4SmsTimer == nil {
                    self.showImageTextToast(in: self.view, text: "Enviado con éxito", image: UIImage.init(named: "icon_success22")!)

                    self.M4SmsTimeInterval = 60
                    self.M4SmsTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.M4TimerCut(timer:)), userInfo: nil, repeats: true)
                    RunLoop.main.add(self.M4SmsTimer!, forMode: .common)
                    
                    let a = Int(Date().timeIntervalSince1970)
                    UserDefaults.standard.setValue(a, forKey: "msm_code_start")
                }
                self.codeData.1 = true
            }
            else {
                self.M4SendCodeButton.M4EventUnavailable = false
                self.showImageTextToast(in: self.view, text: model.message ?? "", image: UIImage.init(named: "icon_fail22")!)

                self.codeData.1 = false
            }
        }
    }
    
    
    private func M4VozCodeNet() {
        self.isHwatsCheckCOde = 0

        codeData.0 = Int(Date().timeIntervalSince1970 * 1000)
        let phone = "52\(M4LoginNumberTF.text ?? "")"
        let param: [String : Any] = ["NTFJSQWe": "ESP", "IKu": M4UserDataManager.m4UserShare.M4Itemcode, "WvUJSd": phone, "Sfag": "2", "WcavLQlhe": "adjust", "XdJvZ": M4UserDataManager.m4UserShare.adjustIdfa, "SXGJ": M4UserDataManager.m4UserShare.adjustAdid, "OSjvU": M4UserDataManager.m4UserShare.adjustIdfv, "USg": "Apple"]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4vozCode, .post, params: param)) { model in
            if model.code == 1 {
                self.showImageTextToast(in: self.view, text: "Enviado con éxito", image: UIImage.init(named: "icon_success22")!)
                self.isHwatsCheckCOde = 0

                if self.M4VozTimer == nil {
                    
                    let a = Int(Date().timeIntervalSince1970)
                    UserDefaults.standard.setValue(a, forKey: "voz_code_start")
                    
                    self.M4VozTimeInterval = 60
                    self.M4VozTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.M4TimerCut(timer:)), userInfo: nil, repeats: true)
                    RunLoop.main.add(self.M4VozTimer!, forMode: .common)
                }
                self.codeData.1 = true
            }
            else {
                self.M4SendCodeButton.M4EventUnavailable = false
                self.showImageTextToast(in: self.view, text: model.message ?? "", image: UIImage.init(named: "icon_fail22")!)
                self.codeData.1 = false
            }
        }
    }
    
    private func M4WhatsCodeNet() {
        self.isHwatsCheckCOde = 0

        codeData.0 = Int(Date().timeIntervalSince1970 * 1000)
        let phone = "52\(M4LoginNumberTF.text ?? "")"
        let param: [String : Any] = ["WIxTO": "ESP", "ChtW": M4UserDataManager.m4UserShare.M4Itemcode, "Taxz": phone, "JYJBl": "7", "IrWk": "adjust", "JtJQG": M4UserDataManager.m4UserShare.adjustIdfa, "Hsan": M4UserDataManager.m4UserShare.adjustAdid, "AfgFS": M4UserDataManager.m4UserShare.adjustIdfv, "WJVWZb": "Apple"]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4smsCode, .post, params: param)) { model in
            if model.code == 1 {
                self.showImageTextToast(in: self.view, text: "Enviado con éxito", image: UIImage.init(named: "icon_success22")!)
                self.isHwatsCheckCOde = 1

                if self.M4WhatsTimer  == nil {
                    
                    let a = Int(Date().timeIntervalSince1970)
                    UserDefaults.standard.setValue(a, forKey: "Whats_code_start")
                    
                    self.M4WhatsTimeInterval = 60
                    self.M4WhatsTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.M4TimerCut(timer:)), userInfo: nil, repeats: true)
                    RunLoop.main.add(self.M4WhatsTimer!, forMode: .common)
                }
                self.codeData.1 = true
            }
            else {
                self.M4SendCodeButton.M4EventUnavailable = false
                self.showImageTextToast(in: self.view, text: model.message ?? "", image: UIImage.init(named: "icon_fail22")!)
                self.codeData.1 = false
            }
        }
    }
    
    private func M4LoginNet(complete: @escaping () -> Void) {
        let phone = "52\(M4LoginNumberTF.text ?? "")"
        let param: [String : Any] = ["WNYzA": "ESP", "DLQlgz": M4UserDataManager.m4UserShare.M4Itemcode, "XwbzZLYZxBn": phone, "Ltu": M4LoginCodeTF.text ?? "", "HlgckPL": M4UserDataManager.m4UserShare.M4Itemcode, "Bgf": M4UserDataManager.m4UserShare.M4Version, "OpMtQEL": M4UserDataManager.m4UserShare.M4BundleID, "VvVmTuX": "Apple", "PjDM":M4UserDataManager.m4UserShare.adjustAdid, "EWtBifBi": M4DeviceModel(), "NObPfpXbEHu": "adjust", "WyAJATtFcM": M4UserDataManager.m4UserShare.adjustIdfa, "Dzrx": M4UserDataManager.m4UserShare.adjustAdid, "TfE": M4UserDataManager.m4UserShare.adjustIdfv,"pRbTYG":"\(isHwatsCheckCOde)"]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4login, .post, params: param), false) { model in
            complete()
            if model.code == 1 {
                
                let data = model.data as? [String : Any]
                let sessionID = data?["EEuqs"] as? String ?? ""
                let isAudit = data?["WtNe"] as? Int ?? 0
                let appUserId = data?["jhw2Q"] as? String ?? ""
                let userName = data?["vaxge"] as? String ?? ""
                M4UserDataManager.m4UserShare.M4appUserId = appUserId
                M4UserDataManager.m4UserShare.M4userName = userName
                
                M4UserDataManager.m4UserShare.M4Token = sessionID
                M4UserDataManager.m4UserShare.M4AuditAccount = isAudit
                M4UserDataManager.m4UserShare.M4UserMobile = self.M4LoginNumberTF.text ?? ""
                M4LimitVerification().M4LimitRequest {
                    DispatchQueue.main.async {
                        if self.M4IsRegister == 0 {
                            M4PublicNetwork.M4CreditStatusAndInfos { isSuccess in
                                if isSuccess {
                                    var vc: UIViewController?
                                    if M4CreditStatusManager.m4CreditShare.m4LoanCredit == "0" {
                                        vc = M4CrediteInfoViewController()
                                    } else {
                                        vc = M4FirstInfoViewController()
                                    }
                                    let nav = M4UINavigationController(rootViewController: vc!)
                                    AppDelegate.keyWindow()?.rootViewController = nav
                                }
                                else {
                                    AppDelegate.keyWindow()?.rootViewController = M4TabBarViewController()
                                }
                            }
                        }
                        else {
                            AppDelegate.keyWindow()?.rootViewController = M4TabBarViewController()
                        }
                        
                        self.uploadData()
                    }
                }
            }
            else {
                self.M4LoginButton.M4EventUnavailable = false
                self.showImageTextToast(in: self.view, text: model.message ?? "", image: UIImage.init(named: "icon_fail22")!)

            }
        }
    }
    
    
    func uploadData() {
        let params: [[String:Any]] = [
            [
                "adga" : 1002,
                "sdqw" : inTime,
                "hgjyj" : Int(Date().timeIntervalSince1970 * 1000) ,
                "akgjrt" : M4DeviceDataManager.m4DeviceShare.m4KEVROxIl - phoneBeginTime
            ],
            [
                "adga" : 1003,
                "akdhef" : codeData.0,
                "Kjdef" : codeData.1==true ? 1 : 0
            ]
        ]
        
        M4HiddenPointDataManager.M4UploadHiddenPoint(type: .Login, paramsKey: "DASdqwr", params: params, complete: nil)
    }
}

extension M4LoginViewController: UITextFieldDelegate {
    
    
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let textString = textField.text else {return true}
        let length = textString.count + string.count - range.length
        if textField == M4LoginNumberTF {
            if textString.prefix(2) == "52" && length <= 12 {
                if length == 12 && (M4SmsTimer == nil && M4VozTimer == nil) {
                    M4ChangeCodeBtnUI(light: true)
                }
                else {
                    M4ChangeCodeBtnUI(light: false)
                }
                return true
            }
            else if length <= 10 {
                if length == 10 && (M4SmsTimer == nil && M4VozTimer == nil) {
                    M4ChangeCodeBtnUI(light: true)
                }
                else {
                    M4ChangeCodeBtnUI(light: false)
                }
                return true
            }
        }
        else if textField == M4LoginCodeTF {
            if length <= 4 {
                if length == 4 {
                    M4LoginButton.setTitleColor(.white, for: .normal)
                    M4LoginButton.backgroundColor = COLOR_00479D
                    M4LoginButton.M4EventUnavailable = false
                }
                else {
                    M4LoginButton.setTitleColor(COLOR_666666, for: .normal)
                    M4LoginButton.backgroundColor = COLOR_EFEFEF
                    M4LoginButton.M4EventUnavailable = true
                }
                return true
            }
        }
        return false
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == M4LoginNumberTF {
            phoneBeginTime = Int(Date().timeIntervalSince1970 * 1000)
            M4DeviceDataManager.m4DeviceShare.m4phoneBeginTime = phoneBeginTime
        }
        
        
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField == M4LoginNumberTF {
            M4DeviceDataManager.m4DeviceShare.m4KEVROxIl = (Int(Date().timeIntervalSince1970 * 1000))


        }
    }
    
}
